package com.lixinkeji.base

import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.drake.logcat.LogCat
import com.drake.statusbar.immersive
import com.drake.statusbar.statusPadding
import com.drake.tooltip.dialog.BubbleDialog
import com.lixinkeji.base.databinding.CommonLayoutBinding
import com.lixinkeji.extension.applyVisible
import com.lixinkeji.extension.onClick
import com.lixinkeji.utils.AppUtil
import com.lixinkeji.utils.DisplayUtil
import com.tianma.netdetector.lib.NetStateChangeObserver
import com.tianma.netdetector.lib.NetStateChangeReceiver
import com.tianma.netdetector.lib.NetworkType

abstract class BaseActivity<T : ViewBinding> : AppCompatActivity(), NetStateChangeObserver {
    abstract fun getViewBinding(): T
    lateinit var binding: T
    private lateinit var mainBinding: CommonLayoutBinding

    //标题文本
    open fun title(): String = ""

    open fun isCanExit(): Boolean = false

    //返回文本
    open fun blackText(): String = ""

    //返回图标
    open fun blackImage(): Int = R.mipmap.black

    //标题颜色
    open fun titleColor(): Int = 0

    //返回文本颜色
    open fun blackColor(): Int = 0

    //文本菜单颜色
    open fun textMenuColor(): Int = 0

    //标题右边图标
    open fun titleRightIcon(): Int = 0

    //右边文本按钮
    open fun textMenuContent(): String = ""
    open fun textMenuContent2(): String = ""
    open fun setTextMenuContent(content: String) {
        mainBinding.textMenu.text = content
    }
    open fun setTextMenuContent2(content: String) {
        mainBinding.textMenu2.text = content
    }

    open fun textBg(): Boolean = false

    //右边图片按钮
    open fun imageMenu(): Int = 0

    //是否隐藏标题栏  false 显示  true 隐藏
    open fun topBarHide(): Boolean = false

    //是否需要状态的宽度
    open fun startPadding(): Boolean = true

    //深色状态栏 true 深色 false 浅色
    open fun darkMode(): Boolean = true
    open fun darkMode(darkMode: Boolean) {
        immersive(darkMode = darkMode)
    }

    open fun backgroundColor(): Int = Color.WHITE
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DisplayUtil.setDefaultDisplay(this)
        Log.e("进入页面", this.javaClass.name)
//        if (this::mainBinding.isInitialized) mainBinding.root.removeAllViews()
//        mainBinding = CommonLayoutBinding.inflate(layoutInflater)
//        val cls =
//            (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<T>
//        setContentView(mainBinding.root)


        try {
//            binding = cls.getMethod("inflate", LayoutInflater::class.java)
//                .invoke(null, LayoutInflater.from(this)) as T
//            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN or WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
            binding = getViewBinding()
            mainBinding = CommonLayoutBinding.inflate(layoutInflater)
            setContentView(mainBinding.root)
            mainBinding.content.addView(binding.root, -1, -1)
        } catch (e: Exception) {
            LogCat.e(e)
        }
//        setDefaultDisplay()
        mainBinding.root.setBackgroundColor(backgroundColor())
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
        iniTitleBar()
        iniView()
        darkMode(darkMode())
        onData()
        onClick()
    }


    //数据填充
    open fun onData() {}

    open fun topBarBackgroundColor() = Color.WHITE

    //点击事件
    open fun onClick() {}
    fun getTextMenu(): TextView = mainBinding.textMenu
    fun getTextMenu2(): TextView = mainBinding.textMenu2

    fun setTitle(title: String) {
        mainBinding.title.text = title
    }


    override fun onDestroy() {
        super.onDestroy()
        overridePendingTransition(0, 0)
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun iniTitleBar() {
        mainBinding.start.statusPadding()
        mainBinding.start.applyVisible(startPadding())
        mainBinding.topBar.applyVisible(!topBarHide())
        mainBinding.blackImage.applyVisible(blackText().isEmpty())
        mainBinding.title.text = title()
        mainBinding.blackText.text = blackText()
        mainBinding.textMenu.text = textMenuContent()
        mainBinding.textMenu2.text = textMenuContent2()
        mainBinding.topBar.setBackgroundColor(topBarBackgroundColor())
        if (textBg()) {
            mainBinding.textMenu.setBackgroundResource(R.drawable.blue_btn)
            mainBinding.textMenu2.setBackgroundResource(R.drawable.blue_btn)
        }
        if (titleColor() != 0) mainBinding.title.setTextColor(getColor(titleColor()))
        if (blackColor() != 0) mainBinding.blackText.setTextColor(
            getColor(
                blackColor()
            )
        )
        if (textMenuColor() != 0) mainBinding.textMenu.setTextColor(textMenuColor())
        if (textMenuColor() != 0) mainBinding.textMenu2.setTextColor(textMenuColor())
        if (blackImage() != 0) mainBinding.blackImage.setImageResource(blackImage())
        if (imageMenu() != 0) mainBinding.imageMenu.setImageResource(imageMenu())

        if (titleRightIcon() != 0) {
            val rightIcon = this.getDrawable(titleRightIcon());
            rightIcon?.setBounds(0, 0, rightIcon.minimumWidth, rightIcon.minimumHeight);
            mainBinding.title.setCompoundDrawables(null, null, rightIcon, null)
        }

        mainBinding.blackText.onClick {
            onBlackListener()
        }
        mainBinding.blackImage.onClick {
            Log.e("TAG", "iniTitleBar: ")
            onBlackListener()
        }
        mainBinding.imageMenu.onClick {
            onImageMenuListener()
        }
        mainBinding.textMenu.onClick {
            onTextMenuListener()
        }
        mainBinding.textMenu2.onClick {
            onTextMenuListener()
        }
    }

    //返回按钮监听
    open fun onBlackListener() {
        finish()
    }

    //右边文本按钮监听
    open fun onTextMenuListener() {

    }

    //右边图片按钮监听
    open fun onImageMenuListener() {}
    abstract fun iniView()
    private var exitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (isCanExit()) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    Toast.makeText(
                        applicationContext,
                        "再按一次退出",
                        Toast.LENGTH_SHORT
                    ).show()
                    exitTime = System.currentTimeMillis()
                } else {
                    BaseApplication.get().exit()
                }
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }





    private var dialog: BubbleDialog? = null
    protected fun showProgress(content: String = "加载中...", isCancel: Boolean = true) {
        if (dialog != null && dialog!!.isShowing) {
            return
        }
        dialog = BubbleDialog(this, content)
        dialog!!.setCancelable(isCancel)
        dialog!!.show()
    }

    protected fun hidProgress() {
        dialog?.apply {
            if (isShowing) dismiss()
        }
    }

    /**
     * 点击空白处或滑动时候隐藏软键盘
     * parent里面下如果有scrollview占据整个画面的话，必须resLayout=scrollview_resid，不然监听不到
     */
    protected open fun hideParentSoftKeyborad(resLayout: Int) {
        //以前的：点空白处隐藏软键盘
//        findViewById(resLayout).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                LogUtil.d("===hideParentSoftKeyborad = onClick");
//                AppUtil.hideSoftKeyboard(instance);
//            }
//        });
        findViewById<View>(resLayout).setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent): Boolean {
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> AppUtil.hideSoftKeyboard(this@BaseActivity)
                    MotionEvent.ACTION_MOVE -> AppUtil.hideSoftKeyboard(this@BaseActivity)
                }
                return false
            }
        })
    }

//    override fun attachBaseContext(newBase: Context?) {
//        super.attachBaseContext(getConfigurationContext(newBase))
//    }

//    private fun getConfigurationContext(context: Context?): Context? {
//        if (context == null) {
//            return null
//        }
//        val configuration = context.resources.configuration
//        configuration.fontScale = 1f
//        return context.createConfigurationContext(configuration)
//    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        if(newConfig.fontScale!=1f){
            getResources()
        }
        super.onConfigurationChanged(newConfig)
    }

    override fun getResources(): Resources {
        var res = super.getResources()
        if(res.configuration.fontScale!=1f){
            var newConfig = Configuration()
            newConfig.setToDefaults()
            res.updateConfiguration(newConfig,res.displayMetrics)
        }
        return res
    }


    fun setDefaultDisplay() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            val res = resources;
            val configuration = res.configuration;
            if (res.displayMetrics.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE){
                    configuration.densityDpi = DisplayMetrics.DENSITY_DEVICE_STABLE;
                    res.updateConfiguration(configuration, res.displayMetrics);
                }
        }
    }

    override fun onResume() {
        super.onResume()
        if (needRegisterNetworkChangeObserver()) {
            NetStateChangeReceiver.registerObserver(this);
        }
    }

    override fun onStop() {
        super.onStop()
        if (needRegisterNetworkChangeObserver()) {
            NetStateChangeReceiver.unregisterObserver(this);
        }
    }

    /**
     * 是否需要注册网络变化的Observer,如果不需要监听网络变化,则返回false;否则返回true.默认返回false
     */
    protected open fun needRegisterNetworkChangeObserver(): Boolean {
        return false
    }

    override fun onNetDisconnected() {}

    override fun onNetConnected(networkType: NetworkType?) {}

}